#include "indexbuffer_directx9.h"
#include "renderer_directx9.h"

namespace gecko
{

IndexBuffer_DirectX9::IndexBuffer_DirectX9()
{

}

IndexBuffer_DirectX9::~IndexBuffer_DirectX9()
{

}

bool IndexBuffer_DirectX9::Initialise(IRenderer *r, unsigned int size, bool dynamic)
{
	m_renderer = static_cast<Renderer_DirectX9*>(r);
	m_uiSize = size;

	m_bDynamic = dynamic;
	D3DPOOL pool = dynamic ? D3DPOOL_DEFAULT : D3DPOOL_MANAGED;
	DWORD usage = dynamic ? D3DUSAGE_WRITEONLY | D3DUSAGE_DYNAMIC : D3DUSAGE_WRITEONLY; 

	if( FAILED(m_renderer->GetD3DDevice()->CreateIndexBuffer(size * sizeof(unsigned short), usage, D3DFMT_INDEX16, pool, &m_pIB, NULL)) )
	{
		return false;
	}

	return true;
}

bool IndexBuffer_DirectX9::Lock(unsigned int offset, unsigned int size, unsigned short** indices)
{
	DWORD dwFlags = m_bDynamic ? D3DLOCK_DISCARD : 0;
	if( FAILED(m_pIB->Lock(offset, size * sizeof(unsigned short), (void**)indices, dwFlags)) )
	{
		return false;
	}

	return true;
}

bool IndexBuffer_DirectX9::Unlock()
{
	m_pIB->Unlock();

	return true;
}

bool IndexBuffer_DirectX9::Destroy()
{
	if ( m_pIB )
	{
		m_pIB->Release();
	}

	return true;
}

bool IndexBuffer_DirectX9::OnLostDevice()
{
	if ( m_bDynamic )
	{
		if (m_pIB)
		{
			m_pIB->Release();
			m_pIB = NULL;
		}
	}

	return true;
}

bool IndexBuffer_DirectX9::OnResetDevice()
{
	if ( m_bDynamic )
	{
		if( FAILED(m_renderer->GetD3DDevice()->CreateIndexBuffer(m_uiSize * sizeof(unsigned short), D3DUSAGE_WRITEONLY | D3DUSAGE_DYNAMIC, D3DFMT_INDEX16, D3DPOOL_DEFAULT, &m_pIB, NULL)) )
		{
			return false;
		}
	}

	return true;
}

}
